#!/usr/bin/python
# encoding: utf-8

import codecs
import os
import re
import keystrokes

class MacKeyStrokes(keystrokes.KeyStrokes):
	
	def getKeyCommand(self,key):
		try:
			return self.decorateWithModifiers(u"key code %s" % int(key))
		except ValueError:
			return self.decorateWithModifiers(u"keystroke %s" % key)
	
	def getStringCommand(self, string):
		return self.decorateWithModifiers(u'keystroke "%s"' % string.replace('"',r'\"'))
	
	def getModifierDecoration(self):
		return u"%%s using %s" % (" & ".join(["%s down" % s for s in self.modifierQueue]))
		

def main(env):
	text = env["context"]["selection"]
	source = """tell application "System Events"\n%s\nset frontmost of process "Chewing Word" to true\nend tell""" % MacKeyStrokes(env).parse(text)
	if env["meta"]["richSuffix"]:
		application = env["meta"]["richSuffix"]
		source = """tell application "%s"\nactivate\n%s\nend tell""" % (application,source)
	codecs.open("log.scpt","w","utf8").write(source)
	os.system("osascript log.scpt")
	return [("replace","")]
